#include "kernel.h"
#include "thread.h"
#include "threadqueue.h"
#include <sysdefines.h>

int kcreate_thread(int pid, int rip, int rsp) {
	int ret = ALL_OK;
	int new_thread;
	
	LOCK4WRITE(&thread_table_lock);
	new_thread = allocate_thread();
	RELEASE_LOCK(&thread_table_lock);
	
	if (new_thread == -1 || new_thread >= MAX_NUMBER_OF_THREADS) {
		ret = ERROR;
	} else {
		LOCK4WRITE(&process_table_lock);
		process_table[pid].threads++;
		RELEASE_LOCK(&process_table_lock);
		
		LOCK4WRITE(&ready_queue_lock);
		LOCK4WRITE(&thread_table_lock);
		thread_table[new_thread].data.registers.integer_registers.rflags = 0x200; // set IF (interrupt flag); enable interrupts		http://en.wikipedia.org/wiki/IF_(x86_flag)
		thread_table[new_thread].data.owner = pid; // The new process owns the new thread.
		if (rsp != -1) {
			thread_table[new_thread].data.registers.integer_registers.rsp = rsp;
		}
		thread_table[new_thread].data.start_stack = rsp;
		thread_table[new_thread].data.registers.integer_registers.rip = rip;
		
		/* Enqeue the new thread for execution */
		thread_queue_enqueue(&ready_queue, new_thread);
		RELEASE_LOCK(&thread_table_lock);
		RELEASE_LOCK(&ready_queue_lock);
	}
	return ret;
}
